from dataclasses import dataclass

from moviepy.Clip import Clip
from moviepy.Effect import Effect
import numpy as np



@dataclass
class FadeInAndOut(Effect):
    """ 淡入淡出效果
    开头淡入 -> delay ~ (delay + effect_duration)
    结尾淡出 -> (total_duration - effect_duration) ~ total_duration
    """

    # 效果持续时长
    effect_duration: float

    # 切片总时长
    total_duration: float

    # 效果出现的时间偏移量
    delay: float

    def apply(self, clip: Clip) -> Clip:
        def calculate_opacity(get_frame, t):
            if self.delay <= t <= self.total_duration + self.delay:
                if t <= self.effect_duration + self.delay:
                    frame = (t - self.delay) / self.effect_duration * get_frame(t)
                    return frame
                elif t > self.total_duration + self.delay - self.effect_duration:
                    frame = (self.total_duration - t) / self.effect_duration * get_frame(t)
                    return frame
                else:
                    return get_frame(t)
            else:
                return get_frame(t) * 0
        return clip.transform(calculate_opacity)
